<template>
  <div class="login-container">
    <div class="login-background"></div>
    
    <div class="login-card">
      <div class="login-header">
        <div class="login-logo">
          <el-icon class="logo-icon"><OfficeBuilding /></el-icon>
        </div>
        <h1 class="login-title">房地产物业管理系统</h1>
        <div class="login-subtitle">Property Management System</div>
      </div>
      
      <el-form 
        class="login-form" 
        :model="loginForm" 
        ref="loginFormRef"
        :rules="loginRules"
      >
        <el-form-item prop="username">
          <el-input 
            v-model="loginForm.username" 
            placeholder="请输入用户名" 
            prefix-icon="User"
            size="large"
            clearable
            @keyup.enter="handleLogin"
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input 
            v-model="loginForm.password" 
            placeholder="请输入密码" 
            prefix-icon="Lock"
            size="large"
            show-password
            @keyup.enter="handleLogin"
          />
        </el-form-item>
        
        <div class="remember-container">
          <el-checkbox v-model="loginForm.remember" label="记住我" size="large" />
          <el-link type="primary" :underline="false">忘记密码?</el-link>
        </div>
        
        <el-form-item>
          <el-button 
            type="primary" 
            :loading="loading" 
            class="login-button" 
            @click="handleLogin"
            size="large"
          >
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
      </el-form>
      
      <div class="login-footer">
        <p>© {{ currentYear }} 房地产物业管理系统 - 版权所有</p>
      </div>
    </div>
    
    <div class="login-decoration">
      <img src="../../assets/login/decoration1.png" alt="装饰" class="decoration-1" />
      <img src="../../assets/login/decoration2.png" alt="装饰" class="decoration-2" />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from "vue-router";
import { ElMessage } from 'element-plus';
import { User, Lock, OfficeBuilding } from '@element-plus/icons-vue';
import axios from 'axios';

const router = useRouter();
const loading = ref(false);
const loginFormRef = ref(null);
const currentYear = new Date().getFullYear();

// 登录表单数据
const loginForm = reactive({
  username: '',
  password: '',
  remember: false
});

// 表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应在3-20个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
};

// 自动填充记住的用户名
onMounted(() => {
  const savedUsername = localStorage.getItem('rememberedUsername');
  if (savedUsername) {
    loginForm.username = savedUsername;
    loginForm.remember = true;
  }
});

// 登录处理
const handleLogin = async () => {
  if (!loginFormRef.value) return;
  
  await loginFormRef.value.validate(async (valid) => {
    if (!valid) return;
    
    try {
      loading.value = true;
      
      // 修改为使用Sa-Token的登录接口
      const response = await axios.post('/api/satoken/login', {
        username: loginForm.username,
        password: loginForm.password
      });
      
      // 记住用户名
      if (loginForm.remember) {
        localStorage.setItem('rememberedUsername', loginForm.username);
      } else {
        localStorage.removeItem('rememberedUsername');
      }
      
      // 登录成功，保存 token 和登录状态
      localStorage.setItem('token', response.data.token);
      localStorage.setItem('username', response.data.user.username);
      localStorage.setItem('isLogin', '1');
      
      // 保存用户角色和权限
      if (response.data.roles && response.data.roles.length > 0) {
        localStorage.setItem('userRoles', JSON.stringify(response.data.roles));
        console.log('保存的角色:', response.data.roles);
      }
      
      // 保存权限列表
      if (response.data.permissions && response.data.permissions.length > 0) {
        localStorage.setItem('permissions', JSON.stringify(response.data.permissions));
        console.log('保存的权限:', response.data.permissions);
      } else {
        // 如果没有权限，根据角色添加默认权限
        if (response.data.roles) {
          let defaultPermissions = [];
          
          // 为admin用户添加所有权限
          if (response.data.roles.includes('ROLE_ADMIN')) {
            defaultPermissions = [
              "VIEW_SYSTEM_DASHBOARD", "MANAGE_USERS", "MANAGE_ROLES", "MANAGE_PERMISSIONS",
              "VIEW_COMMUNITY", "MANAGE_COMMUNITY", "VIEW_BUILDING", "MANAGE_BUILDING",
              "VIEW_HOUSE", "MANAGE_HOUSE", "VIEW_OWNER", "MANAGE_OWNER",
              "VIEW_VEHICLE", "MANAGE_VEHICLE", "VIEW_PARKING", "MANAGE_PARKING",
              "VIEW_PARKING_USAGE", "MANAGE_PARKING_USAGE", "VIEW_SERVICE", "VIEW_ACTIVITY",
              "MANAGE_ACTIVITY", "VIEW_REPAIR", "MANAGE_REPAIR", "VIEW_COMPLAINT",
              "MANAGE_COMPLAINT", "VIEW_MAILBOX", "MANAGE_MAILBOX"
            ];
          } 
          // 为物业管理员添加物业相关权限
          else if (response.data.roles.includes('ROLE_PROPERTY_ADMIN')) {
            defaultPermissions = [
              "VIEW_COMMUNITY", "MANAGE_COMMUNITY", "VIEW_BUILDING", "MANAGE_BUILDING",
              "VIEW_HOUSE", "MANAGE_HOUSE", "VIEW_OWNER", "MANAGE_OWNER",
              "VIEW_VEHICLE", "MANAGE_VEHICLE", "VIEW_PARKING", "MANAGE_PARKING",
              "VIEW_PARKING_USAGE", "MANAGE_PARKING_USAGE", "VIEW_SERVICE", "VIEW_ACTIVITY",
              "MANAGE_ACTIVITY", "VIEW_REPAIR", "MANAGE_REPAIR", "VIEW_COMPLAINT",
              "MANAGE_COMPLAINT", "VIEW_MAILBOX", "MANAGE_MAILBOX"
            ];
          }
          // 为业主添加查看相关权限
          else if (response.data.roles.includes('ROLE_OWNER')) {
            defaultPermissions = [
              "VIEW_COMMUNITY", "VIEW_BUILDING", "VIEW_HOUSE", 
              "VIEW_PARKING", "VIEW_PARKING_USAGE", "VIEW_ACTIVITY",
              "VIEW_REPAIR", "VIEW_COMPLAINT", "VIEW_MAILBOX"
            ];
          }
          
          localStorage.setItem('permissions', JSON.stringify(defaultPermissions));
          console.log('为角色添加的默认权限:', defaultPermissions);
        }
      }
      
      ElMessage({
        message: '登录成功，欢迎回来！',
        type: 'success'
      });
      
      // 跳转到首页
      router.replace("/");
    } catch (error) {
      console.error('Login error:', error);
      
      let errorMsg = '登录失败';
      if (error.response) {
        errorMsg = error.response.data.message || '用户名或密码错误';
      } else if (error.request) {
        errorMsg = '网络连接错误，请检查您的网络';
      } else {
        errorMsg = '登录过程中发生错误';
      }
      
      ElMessage({
        message: errorMsg,
        type: 'error'
      });
    } finally {
      loading.value = false;
    }
  });
};
</script>

<style scoped>
.login-container {
  width: 100%;
  height: 100vh;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
}

.login-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url(../../assets/login/bg.png);
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  filter: brightness(0.9);
  z-index: -1;
}

.login-card {
  width: 460px;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 12px;
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.2);
  padding: 40px;
  position: relative;
  z-index: 10;
  backdrop-filter: blur(10px);
  animation: fadeIn 0.8s ease-out;
}

.login-header {
  text-align: center;
  margin-bottom: 40px;
}

.login-logo {
  display: flex;
  justify-content: center;
  margin-bottom: 16px;
}

.logo-icon {
  font-size: 48px;
  color: #409EFF;
}

.login-title {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.login-subtitle {
  font-size: 16px;
  color: #909399;
  margin-bottom: 20px;
}

.login-form {
  margin-bottom: 24px;
}

.login-form :deep(.el-input__wrapper) {
  padding: 12px 15px;
  font-size: 16px;
}

.login-form :deep(.el-input__prefix-inner) {
  font-size: 20px;
}

.remember-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.login-button {
  width: 100%;
  height: 50px;
  font-size: 18px;
  font-weight: 500;
  letter-spacing: 2px;
}

.login-footer {
  text-align: center;
  margin-top: 30px;
  color: #909399;
  font-size: 14px;
}

.login-decoration {
  position: absolute;
  z-index: 1;
  pointer-events: none;
}

.decoration-1 {
  position: absolute;
  width: 300px;
  bottom: -50px;
  left: -150px;
  opacity: 0.8;
  animation: float 6s ease-in-out infinite;
}

.decoration-2 {
  position: absolute;
  width: 350px;
  top: -100px;
  right: -150px;
  opacity: 0.7;
  animation: float 8s ease-in-out infinite reverse;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes float {
  0% {
    transform: translateY(0px);
  }
  50% {
    transform: translateY(-20px);
  }
  100% {
    transform: translateY(0px);
  }
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .login-card {
    width: 90%;
    max-width: 460px;
    padding: 30px 20px;
  }
  
  .login-title {
    font-size: 24px;
  }
  
  .decoration-1,
  .decoration-2 {
    display: none;
  }
}

@media screen and (max-height: 700px) {
  .login-card {
    padding: 20px;
  }
  
  .login-header {
    margin-bottom: 20px;
  }
  
  .login-footer {
    margin-top: 15px;
  }
}
</style>
